<?php
namespace Application\Admin\Controller;

class Model extends Base
{

    public function init()
    {
        $this->setDir('model');
        $this->setTemplate('field', 'field');
    }

    public function _initRoute()
    {
        $data = [
            'path_new' => '/Admin/Model/new',
            'path_edit' => '/Admin/Model/edit',
            'path_index' => '/Admin/Model/index',
            'path_show' => '/Admin/Model/show',
            'path_delete' => '/Admin/Model/delete'
        ];
        $this->setCommonData($data);
    }

    private function getService()
    {
        return $this->get(SERVICE_MODEL);
    }

    public function indexAction()
    {
        $this->setFile($this->getTemplateIndex());
        $this->show();
    }

    public function newAction()
    {
        $this->setFile($this->getTemplateNew());
        $this->setData(['action' => 'new']);
        $this->show();
    }

    public function editAction()
    {
        $data = $this->getRequestData();
        $rs = $this->getService()->one($data['id']);
        $this->setFile($this->getTemplateEdit());
        $this->setData(['action' => 'edit', 'rs' => $rs]);
        $this->show();
    }

    public function showAction()
    {
        $data = $this->getRequestData();
        $rs = $this->getService()->one($data['id']);
        $this->setFile($this->getTemplateShow());
        $this->setData(['action' => 'show', 'rs' => $rs]);
        $this->show();
    }

    private function getKey($modelId, $field)
    {
        return "field_sql_{$modelId}_{$field}";
    }

    public function fieldAction()
    {
        $data = $this->getRequestData();
        $serviceSystem = $this->get(SERVICE_SYSTEM);
        $cacheModel = $this->get(CACHE_MODEL);
        $modelId = (int)$data['id'];
        $model = $this->getService()->one($modelId);
        $table = $model->dry_database . '.' . $model->dry_table;
        $tables = $serviceSystem->getTables();
        $twigData = [];
        $twigData['model'] = $model;
        $tableExist = in_array($table, $tables);
        $twigData['table_exist'] = $tableExist;
        $twigData['table_exist_text'] = $tableExist?'存在':'不存在';
        $twigData['create_table_sql'] = $serviceSystem->getCreateTableSql($model->dry_table, $model->dry_note);
        /**/
        $list1 = $serviceSystem->getTableFields($model->dry_database_config_key, $model->dry_table);
        $existFields = array2arrayByKey($list1, 'COLUMN_NAME');
        $existFieldMap = array2mapObject($list1, 'COLUMN_NAME');
        /**/
        $list2 = $this->getService()->getFieldList($modelId);
        $fields = array2arrayByKey($list2, 'dry_field');
        $fieldMap = array2mapObject($list2, 'dry_field');
        /**/
        $allFields = array_merge($existFields, $fields);
        $allFields = array_unique($allFields);
        $list = [];
        $index = 1;
        foreach($allFields as $field){
            $bool1 = in_array($field, $existFields);
            $bool2 = in_array($field, $fields);
            $sql = '';
            /*增加字段*/
            if(!$bool1 && $bool2){
                $sql = $serviceSystem->getAddColumnSql($model->dry_table, $field, $fieldMap[$field]);
            }
            /*删除字段*/
            else if($bool1 && !$bool2){
                $sql = $serviceSystem->getDropColumnSql($model->dry_table, $field);
            }
            /*修改字段*/
            else if($bool1 && $bool2){
                $sql = $serviceSystem->getModifyColumnSql($model->dry_table, $field, $fieldMap[$field]);
            }
            $item = [
                'dry_no' => $index++,
                'dry_field' => $field,
                'dry_current_type' => $bool1?$existFieldMap[$field]->COLUMN_TYPE:'',
                'dry_target_type' => $bool2?$fieldMap[$field]->dry_field_type_data->dry_type:'',
                'exist_text' => $bool1?'存在':'不存在',
                'require_text' => $bool2?'需要':'不需要',
                'sql' => $sql
            ];
            if($item['dry_current_type'] == $item['dry_target_type']){
                $item['sql'] = '';
            }
            $cacheModel->setData($this->getKey($modelId, $field), HALF_HOUR_SECOND, $item['sql']);
            $list[] = $item;
        }
        $twigData['list'] = $list;
        $this->setFile($this->getTemplate('field'));
        $this->setData($twigData);
        $this->show();
    }

    public function createTableAction()
    {
        $data = $this->getRequestData();
        $serviceSystem = $this->get(SERVICE_SYSTEM);
        $modelId = (int)$data['modelId'];
        $model = $this->getService()->one($modelId);
        $serviceSystem->createTable($model->dry_database_config_key, $model->dry_table, $model->dry_note);
        $this->sendSuccess();
    }

    public function adjustFieldAction()
    {
        $data = $this->getRequestData();
        $serviceSystem = $this->get(SERVICE_SYSTEM);
        $cacheModel = $this->get(CACHE_MODEL);
        $modelId = (int)$data['modelId'];
        $field = $data['field'];
        if($modelId <= 0){
            $this->sendFail('PARAMETER_ERROR', '模型ID错误');
        }
        if($field == ''){
            $this->sendFail('PARAMETER_ERROR', '字段错误');
        }
        $model = $this->getService()->one($modelId);
        if(empty($model)){
            $this->sendFail('PARAMETER_ERROR', '模型找不到');
        }
        $sql = $cacheModel->getData($this->getKey($modelId, $field));
        if(empty($sql)){
            $this->sendFail('PARAMETER_ERROR', '操作超时，请刷新页面重试');
        }
        $serviceSystem->adjustField($model->dry_database_config_key, $sql);
        $this->sendSuccess();
    }

}